package com.xianyun.smartpicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xianyun.smartpicturebackend.exception.ErrorCode;
import com.xianyun.smartpicturebackend.exception.ThrowUtils;
import com.xianyun.smartpicturebackend.manager.FileManage;
import com.xianyun.smartpicturebackend.mapper.PictureMapper;
import com.xianyun.smartpicturebackend.model.dto.file.UploadPictureResult;
import com.xianyun.smartpicturebackend.model.dto.picture.PictureQueryRequest;
import com.xianyun.smartpicturebackend.model.dto.picture.PictureUploadRequest;
import com.xianyun.smartpicturebackend.model.entity.Picture;
import com.xianyun.smartpicturebackend.model.entity.User;
import com.xianyun.smartpicturebackend.model.vo.PictureVO;
import com.xianyun.smartpicturebackend.model.vo.UserVO;
import com.xianyun.smartpicturebackend.service.PictureService;
import com.xianyun.smartpicturebackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xianYun
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-02-16 20:57:26
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
    @Resource
    private FileManage fileManage;
    @Resource
    private UserService userService;

    /**
     * 图片信息校验(防止id为空，url过长，简介过长)
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        // 如果传递了 url，才校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 上传图片
     *
     * @param multipartFile        图片
     * @param pictureUploadRequest 标记图片的id
     * @param user                 上传者
     * @return 脱敏后的图片信息
     */
    @Override
    public PictureVO uploadPicture(MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest, User user) {
        //1. 参数校验
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");

        //避免空指针异常
        Long pictureId = null;//pictureId 是由数据库生成的
        if (pictureUploadRequest != null) {//这里不抛出异常的原因是：用户新增图片是，pictureId为空，pictureUploadRequest 可以为空
            pictureId = pictureUploadRequest.getId();
        }
        //2. 确认是更新还是新增
        /*
        如果是更新的话，则会执行下面的if块，如果是新增的话，则不会执行if块
        如果是新增的话，则直接走第三步。
        不管是更新还是新增，都需要上传到COS。
         */
        if (pictureId != null) {
            boolean exists = this.lambdaQuery()
                    .eq(Picture::getId, pictureId)
                    .exists();
            ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR, "数据库中找不到需要更新的图片");
        }
        //3. 上传图片到COS
        //定义上传路径前缀，这里是public/用户id，根据不同的用户来分配不同的存储空间，
        //是public的原因是目前的业务场景是搭建一个公共的图片浏览平台
        String uploadPathPrefix = String.format("%s/%s", "public", user.getId());
        UploadPictureResult uploadPictureResult = fileManage
                .uploadPicture(multipartFile, uploadPathPrefix);
        //封装需要存储到数据库的信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setUserId(user.getId());

        //4. 保存图片信息到数据库
        if (pictureId != null) {
            //如果是更新图片则需要补充更新时间和图片id
            picture.setId(pictureId);
            picture.setUpdateTime(new Date());
        }
        boolean saveOrUpdate = this.saveOrUpdate(picture);
        ThrowUtils.throwIf(!saveOrUpdate, ErrorCode.SYSTEM_ERROR, "图片上传数据库失败");
        return PictureVO.objToVo(picture);
    }

    /**
     * 分页获取图片脱敏信息
     * 目标：将未脱敏的图片信息封装成已脱敏的图片信息
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        //1. 获取未脱敏的图片信息
        List<Picture> picturePageRecords = picturePage.getRecords();//获取分页对象中的具体分页信息
        //2. 创建一个已经脱敏的图片分页对象
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(picturePageRecords)) {
            return pictureVOPage;
        }
        //3. 未脱敏对象信息 => 封装已脱敏的对象信息
        List<PictureVO> pictureVOPageRecords = picturePageRecords.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        // 4. 关联查询用户信息
        // 1,2,3,4
        //将未脱敏的图片列表中的 userId 提取出来，放进set集合（set集合可以自然去重）
        Set<Long> userIdSet = picturePageRecords.stream().map(Picture::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        //listByIds mybatis-plus 提供的批量查询的方法
        Map<Long, List<User>> userMap = userService.listByIds(userIdSet).stream()
                //根据 userId 分组，得到一个map集合，key为userId，value为user集合,方便判断（把List转换成map）
                .collect(Collectors.groupingBy(User::getId));
        // 5. 将与图片关联的用户信息补充道脱敏的图片分页信息中
        pictureVOPageRecords.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userMap.containsKey(userId)) {
                //只获取第一个用户（因为一个id只对应一个用户）
                user = userMap.get(userId).get(0);
            }
            pictureVO.setUserVO(userService.getUserVO(user));
        });
        //6. 将已完成脱敏的图片信息封装到分页对象中
        pictureVOPage.setRecords(pictureVOPageRecords);
        return pictureVOPage;
    }

    /**
     * 获取查询条件
     *
     * @param
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR);
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        /*
        这样包装查询条件，实现了代码解耦，用户传来什么参数我们就根据什么参数构建对象，
        没有传来的参数，就不构建这个参数（通过NotNull实现控制）
         */
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        //ascend 表升序，descend 降序

        //从多字段中查询（searchText 需要从图片名称和图片简介中查询）
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        // < endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询，只有包含所有标签的图片才能被查询出来
        if (CollUtil.isNotEmpty(tags)) {
            /* and (tag like "%\"Java\"%" and like "%\"Python\"%") */
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUserVO(userVO);
        }
        return pictureVO;
    }
}




